package cn.zcltd.btg.httpsession.servlet.filter;

import cn.zcltd.btg.httpsession.BTGSessionDao;
import cn.zcltd.btg.httpsession.impl.BTGDBSessionDao;
import cn.zcltd.btg.httpsession.impl.BTGRedisSessionDao;
import cn.zcltd.btg.httpsession.kit.SessionKit;
import cn.zcltd.btg.httpsession.servlet.BTGHttpServletRequest;
import cn.zcltd.btg.sutil.EmptyUtil;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 注意：此filter优先级必须大于业务系统处理相关filter
 * BTGHttpSessionRequest替换filter(local session管理)
 * 若需要redis、db模式的session管理，请在初始化配置参数init-param：
 * sessionDao：可选，默认为local。local-使用local的BTGSessionDao；redis-使用redis的BTGSessionDao；db-使用redis的BTGSessionDao；
 * dname：可选，默认为jfinal默认；若sessionDao为redis，该参数则表示RedisPlugin的name；若sessionDao为db，该参数表示ActiveRecordPlugin的name；
 * 或者扩展此类，重写init方法完成sessionDao的初始化即可
 */
public class BTGHttpSessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String sessionDaoStr = filterConfig.getInitParameter("sessionDao");
        String dname = filterConfig.getInitParameter("dname");

        BTGSessionDao sessionDao = null;
        if (EmptyUtil.isNotEmpty(sessionDaoStr)) {
            switch (sessionDaoStr.toUpperCase()) {
                case "REDIS":
                    if (EmptyUtil.isNotEmpty(dname)) {
                        sessionDao = new BTGRedisSessionDao(dname);
                    } else {
                        sessionDao = new BTGRedisSessionDao();
                    }
                    break;
                case "DB":
                    if (EmptyUtil.isNotEmpty(dname)) {
                        sessionDao = new BTGDBSessionDao(dname);
                    } else {
                        sessionDao = new BTGDBSessionDao();
                    }
                    break;
            }
        }
        if (EmptyUtil.isNotEmpty(sessionDao)) {
            SessionKit.setSessionDao(sessionDao);
        }

        String useCache = filterConfig.getInitParameter("useCache");
        if (EmptyUtil.isNotEmpty(useCache)) {
            if ("true".equals(useCache)) {
                SessionKit.getSessionContext().setUseCache(true);
            } else {
                SessionKit.getSessionContext().setUseCache(false);
            }
        }

        String sessionTimeoutSeconds = filterConfig.getInitParameter("sessionTimeoutSeconds");
        if (EmptyUtil.isNotEmpty(sessionTimeoutSeconds)) {
            SessionKit.setSessionTimeoutSeconds(Integer.parseInt(sessionTimeoutSeconds));
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = new BTGHttpServletRequest((HttpServletRequest) servletRequest); //替换自定义session的request扩展
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //根据是否开启简单单点登录设置默认cookie path
        if (SessionKit.isDisableSimpleSSO()) {
            SessionKit.setSessionCookiePath(request.getContextPath() + "/");
        }

        //自动设置session cookie
        HttpSession session = request.getSession(false);
        if (EmptyUtil.isEmpty(session)) {
            session = SessionKit.getNewSession();
        }

        Cookie sessionCookie = new Cookie(SessionKit.getSessionIdKey(), session.getId());
        sessionCookie.setPath(SessionKit.getSessionCookiePath());
        sessionCookie.setMaxAge(session.getMaxInactiveInterval());
        response.addCookie(sessionCookie);

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}